package org.ehe.business.workstation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.business.workstation.domain.Workstation;
import org.ehe.business.workstation.domain.bo.WorkstationBo;
import org.ehe.business.workstation.domain.vo.WorkstationVo;
import org.ehe.business.workstation.mapper.WorkstationMapper;
import org.ehe.business.workstation.service.IWorkstationService;
import org.ehe.common.core.exception.ServiceException;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 工位管理Service实现
 *
 * @author zhangnn
 * @date 2025-10-23
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WorkstationServiceImpl extends ServiceImpl<WorkstationMapper, Workstation>
        implements IWorkstationService {

    private final WorkstationMapper workstationMapper;

    @Override
    public TableDataInfo<WorkstationVo> queryPageList(WorkstationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Workstation> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(bo.getCode()), Workstation::getCode, bo.getCode())
                .like(StrUtil.isNotBlank(bo.getName()), Workstation::getName, bo.getName())
                .orderByAsc(Workstation::getId);

        Page<Workstation> page = workstationMapper.selectPage(pageQuery.build(), wrapper);

        // 转换为Vo
        Page<WorkstationVo> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        List<WorkstationVo> voList = page.getRecords().stream()
                .map(this::toVo)
                .collect(Collectors.toList());
        voPage.setRecords(voList);

        return TableDataInfo.build(voPage);
    }

    @Override
    public List<WorkstationVo> queryList(WorkstationBo bo) {
        LambdaQueryWrapper<Workstation> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(bo.getCode()), Workstation::getCode, bo.getCode())
                .like(StrUtil.isNotBlank(bo.getName()), Workstation::getName, bo.getName())
                .orderByDesc(Workstation::getId);

        return workstationMapper.selectList(wrapper).stream()
                .map(this::toVo)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertWorkstation(WorkstationBo bo) {
        // 校验编号格式(4位数字)
        if (StrUtil.isBlank(bo.getCode()) || !bo.getCode().matches("\\d{3}")) {
            throw new ServiceException("工位编号必须为3位数字");
        }

        // 校验编号唯一性
        Workstation exists = workstationMapper.selectByCode(bo.getCode());
        if (exists != null) {
            throw new ServiceException("工位编号已存在，请使用其他编号");
        }

        Workstation workstation = BeanUtil.copyProperties(bo, Workstation.class);
        return workstationMapper.insert(workstation) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateWorkstation(WorkstationBo bo) {
        if (bo.getId() == null) {
            throw new ServiceException("工位ID不能为空");
        }

        // 校验工位是否存在
        Workstation exists = workstationMapper.selectById(bo.getId());
        if (exists == null) {
            throw new ServiceException("工位不存在");
        }

        // 如果修改了编号，校验格式和唯一性
        if (StrUtil.isNotBlank(bo.getCode()) && !bo.getCode().equals(exists.getCode())) {
            if (!bo.getCode().matches("\\d{3}")) {
                throw new ServiceException("工位编号必须为3位数字");
            }
            Workstation codeExists = workstationMapper.selectByCode(bo.getCode());
            if (codeExists != null) {
                throw new ServiceException("工位编号已存在，请使用其他编号");
            }
        }

        Workstation workstation = BeanUtil.copyProperties(bo, Workstation.class);
        return workstationMapper.updateById(workstation) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWorkstations(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new ServiceException("请选择要删除的工位");
        }
        return workstationMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Workstation selectByCode(String workstationCode) {
        return this.baseMapper.selectOne(new LambdaQueryWrapper<Workstation>().eq(Workstation::getCode,workstationCode));
    }

    /**
     * 实体转换为Vo
     */
    private WorkstationVo toVo(Workstation workstation) {
        WorkstationVo vo = new WorkstationVo();
        vo.setId(workstation.getId());
        vo.setCode(workstation.getCode());
        vo.setName(workstation.getName());
        vo.setRemark(workstation.getRemark());
        return vo;
    }
}
